package com.joney.backstage.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.joney.backstage.constant.Constants;
import com.joney.backstage.constant.Permissions;
import com.joney.backstage.constant.WebPageEL;
import com.joney.backstage.dto.ResAddReq;
import com.joney.backstage.dto.ResEditReq;
import com.joney.backstage.entity.Resource;
import com.joney.backstage.entity.RoleResource;
import com.joney.backstage.mapper.ResourceMapper;
import com.joney.backstage.pojo.EasyUITree;
import com.joney.backstage.pojo.MenuTree;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.joney.common.pojo.Result;
import com.joney.common.utils.JudgeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author joney123
 * @since 2018-01-15
 */
@Service
public class ResourceService extends ServiceImpl<ResourceMapper, Resource> {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleResourceService  roleResourceService;
    /**
     * @desc 获取主页左侧导航菜单树
     * @author wangxianchen
     * @create 2018-01-15
     * @return
     */
    public List<MenuTree> getNavigationTree(Integer userId){
        List<MenuTree> menuList = null;
        List<String> permissionList = userRoleService.getPermissions(userId);
        if(permissionList != null && permissionList.size() > 0){
            menuList = baseMapper.selectNavigationTree(Constants.NAVIGATION_TREE_DEFAULT_ROOT_ID);
            if(menuList != null){
                containsPermission(menuList,permissionList);
            }
        }
        return menuList;
    }

    /**
     * 去除没有权限的菜单
     * @param menuList
     * @param permissionList
     */
    public void containsPermission(List<MenuTree> menuList,List<String> permissionList){
        for(int i = menuList.size() - 1; i >= 0; i--){
            if(permissionList.contains(menuList.get(i).getPermission())){
                List<MenuTree> subList = menuList.get(i).getChildren();
                if(subList != null && subList.size() > 0){
                    containsPermission(subList,permissionList);
                }
            }else{
                menuList.remove(i);
            }
        }
    }
    public List<EasyUITree> getResTree(int pId,int filterId){
        List<EasyUITree> list = null;
        if(filterId == 1){
            list = baseMapper.selectLeftMenu(pId);
        }else{
            list = baseMapper.selectResTree(pId);
        }
        return list;
    }

    public List<EasyUITree> getResTree(int pId){
        return baseMapper.selectResTree(pId);
    }

    /**
     * @desc 获取用户所有角色包含的权限资源
     * @author wangxianchen
     * @create 2018-02-07
     * @param userId
     * @return
     */
    public Set<String> getStringPermissionsByUserId(int userId){
        List<Resource> resList = baseMapper.selectResourcesByUserId(userId);
        Set<String> set = new HashSet<>();
        if(JudgeUtil.isNotEmpty(resList)){
            for(Resource res : resList){
                set.add(res.getPermission());
            }
        }
        return set;
    }

    public Map<String,Boolean> getMgrPermission(int curLoginUserId){
        Map<String,Boolean> authMap = new HashMap<>();
        authMap.put(WebPageEL.CAN_ADD,false);
        authMap.put(WebPageEL.CAN_EDIT,false);
        authMap.put(WebPageEL.CAN_DEL,false);
        List<String> permissionList = userRoleService.getPermissions(curLoginUserId);
        if(permissionList != null && permissionList.size() > 0){
            for(String permission : permissionList){
                if(permission != null){
                    if(permission.equals(Permissions.SYS_RES_ADD)){
                        authMap.put(WebPageEL.CAN_ADD,true);
                    }else if(permission.equals(Permissions.SYS_RES_EDIT)){
                        authMap.put(WebPageEL.CAN_EDIT,true);
                    }else if(permission.equals(Permissions.SYS_RES_DEL)){
                        authMap.put(WebPageEL.CAN_DEL,true);
                    }

                }
            }
        }
        return authMap;
    }

    public Result addNode(ResAddReq params, Integer operatorId){
        Resource parent = selectById(params.getParentId());
        if(parent == null){
            return Result.fail("父节点不存在，请刷新重试！");
        }
        Resource temp = new Resource();
        BeanUtils.copyProperties(params,temp);
        temp.setCreateUser(operatorId);
        temp.setLevel(parent.getLevel()+1);
        if(!insert(temp)){
            return Result.fail("保存失败");
        }
        EasyUITree tree = new EasyUITree();
        tree.setId(temp.getId());
        tree.setPId(temp.getParentId());
        tree.setText(temp.getName());
        tree.setLevel(temp.getLevel());
        tree.setResType(temp.getResType());
        return Result.success(new EasyUITree[]{tree});
    }
    /**
     * @desc 递归删除子节点
     * @author wangxianchen
     * @create 2018-05-10
     * @param ids
     */
    public void deleteNodes(String ids){
        String[] idArr = ids.split("-");
        for(String id:idArr){
            remove(Integer.valueOf(id));
        }
    }

    private void remove(Integer pId){
        EntityWrapper<Resource> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id",pId);
        List<Resource> list = selectList(wrapper);
        if(list != null && list.size() >0){
            for(Resource res : list){
                remove(res.getId());
            }
            deleteById(pId);
        }else{ //未查到子节点，则删除当前节点
            deleteById(pId);
        }
    }

    public Result updateNode(ResEditReq params, int operatorId){
        Resource res = selectById(params.getId());
        if(res == null){
            return Result.fail("资源不存在，请刷新重试");
        }
        res = new Resource();
        BeanUtils.copyProperties(params,res);
        res.setUpdateUser(operatorId);
        updateById(res);
        return Result.success();
    }

    public Result moveNote(Integer pId, Integer id, int operatorId){
        Resource pNode = selectById(pId);
        if(pNode == null){
            return Result.fail("资源不存在，请刷新重试");
        }
        Resource curNode = selectById(id);
        if(curNode == null){
            return Result.fail("资源不存在，请刷新重试");
        }
        curNode.setParentId(pId);
        curNode.setLevel(pNode.getLevel()+1);
        curNode.setUpdateUser(operatorId);
        List<Resource> nodeList = new ArrayList<>();
        nodeList.add(curNode);
        List<EasyUITree> list = baseMapper.selectResTree(id);
        if(list!=null){
            setNodeInfo(list,nodeList,curNode,operatorId);
        }
        updateBatchById(nodeList);
        return Result.success();
    }

    private void setNodeInfo(List<EasyUITree> list,List<Resource> nodeList,Resource pNode,int operatorId){
        for(EasyUITree node : list){
            Resource temp = new Resource();
            temp.setId(node.getId());
            temp.setParentId(pNode.getId());
            temp.setLevel(pNode.getLevel()+1);
            temp.setUpdateUser(operatorId);
            nodeList.add(temp);
            if(node.getChildren()!=null){
                setNodeInfo(node.getChildren(),nodeList,temp,operatorId);
            }
        }
    }

    public Result getIconList(){
        File file = new File("E:\\workspace\\a\\web-static\\easyui\\themes\\myicons");
        File[] arr = file.listFiles();
        for(File f:arr){
            if(f.isFile()){
                System.out.println();
            }
        }
        return null;
    }

    public List<EasyUITree> getAuthTree(int roleId){
        List<EasyUITree> treeList = getResTree(Constants.NAVIGATION_TREE_DEFAULT_ROOT_PARENT_ID);
        EntityWrapper<RoleResource> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id",roleId);
        List<RoleResource> roleResList = roleResourceService.selectList(wrapper);
        doCheck(treeList,roleResList);
        return treeList;
    }

    private void doCheck(List<EasyUITree> treeList,List<RoleResource> roleResList){
        if(treeList != null && roleResList != null && roleResList.size() != 0){
            for(EasyUITree tree : treeList){
                for(int i=0;i<roleResList.size();i++){
                    if(tree.getId().equals(roleResList.get(i).getResId())){
                        tree.setChecked(true);
                        roleResList.remove(i);
                        break;
                    }
                }
                doCheck(tree.getChildren(),roleResList);
            }
        }
    }
}
